package com.ply.filter;


import com.alibaba.fastjson.JSONObject;
import com.ply.entity.vo.Result;
import com.ply.utils.TokenUtils;
import com.ply.utils.encoding.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author XiaoPan
 * date: 2022/1/8 12:45
 * <p>
 * action:
 */
//@WebFilter(filterName = "TokenFilter", urlPatterns = "/user/*")
public class TokenFilter implements Filter {
    private static Logger log = LogManager.getLogger(TokenFilter.class.getName());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // TODO 用户token 错误后怎么传递参数 给前端
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html;Charset=utf-8");


        //允许跨域访问，通过response对象写回一些跨域访问的头信息
        response.setHeader("Access-Control-Allow-Origin", "*");
        //允许请求的方法
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");

        response.setHeader("Access-Control-Expose-Headers", "Token");

        response.setHeader("Access-Control-Allow-Headers", "Token");

        response.setHeader("Access-Control-Allow-Credentials", "true");

        String tokenBase64 = request.getHeader("Token");
        String token = Base64.getUtf8(tokenBase64);

        Map<String, Object> map = TokenUtils.getTokenAll(token);
        Integer id = (Integer) map.get("id");
        String type = (String) map.get("type");

        if (!"用户".equals(type)) {
            response.getWriter().write((JSONObject.toJSONString(Result.fail("没有登陆"))));
            return;
        }

        Long expireTime = (Long) map.get("expireTime");
        String md5 = (String) map.get("md5");

        //返回值
//        StringBuilder stringBuilder = new StringBuilder();

//        Result fail = Result.fail("用户登录失败");
//        stringBuilder.append(fail.getCode());
//        stringBuilder.append(fail.getMsg());
//
//        JSON jsonFail = (JSON) JSONObject.parse(stringBuilder.toString());

        if (null == token || "".equals(token)) {
            log.info("没有token");
//            response.getWriter().write(jsonFail.toJSONString());
            response.getWriter().write((JSONObject.toJSONString(Result.fail("没有token"))));
            return;
        }

        if (!TokenUtils.checkToken(id, type, expireTime, md5)) {
            log.info("无效的token");
//            response.getWriter().write(jsonFail.toJSONString());
            response.getWriter().write((JSONObject.toJSONString(Result.fail("无效的token"))));

            return;
        }
        if (!TokenUtils.compareTime(expireTime)) {
            log.info("无效的token");
            response.getWriter().write((JSONObject.toJSONString(Result.fail("token过期"))));
            return;
        }

        log.info("登录成功:{}", id);

        //打印过期时间
        System.out.println(new Date(expireTime));

        UserUtils.setUserId(id);
//        request.setAttribute("userId",id);

        ThreadLocal<Integer> local = new ThreadLocal<>();
        local.set(id);

        //生成新的token
        String newToken = TokenUtils.toToken(id, type);
        //设置响应头
        response.setHeader("Token", newToken);
        //设置新的token
        filterChain.doFilter(servletRequest, servletResponse);

//        UserUtils.clear();
    }


    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
